package cn.demarcia.coco.uihelper;

import android.content.Context;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.StrikethroughSpan;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class StringUtils {
    private final static SimpleDateFormat yMdHmsFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private final static SimpleDateFormat yMdFormater = new SimpleDateFormat("yyyy-MM-dd");
    private final static SimpleDateFormat yMdHmFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    /**
     * 判断给定字符串是否空白串。 空白串是指由空格、制表符、回车符、换行符组成的字符串 若输入字符串为null或空字符串，返回true
     *
     * @param input
     * @return boolean
     */
    public static boolean isEmpty(String input) {
        if (input == null || "".equals(input) || "null".equals(input))
            return true;

        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
                return false;
            }
        }
        return true;
    }

    /**
     * 对象转整数
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static int toInt(Object obj) {
        if (obj == null)
            return 0;
        return toInt(obj.toString(), 0);
    }

    /**
     * 字符串转整数
     *
     * @param str
     * @param defValue
     * @return
     */
    public static int toInt(String str, int defValue) {
        try {
            return Integer.parseInt(str);
        } catch (Exception ignored) {
        }
        return defValue;
    }

    /**
     * 从资源中读取字符串
     *
     * @param context
     * @param strId
     * @return
     */
    public static String getStrFromValues(Context context, int strId) {
        return context.getString(strId);
    }

    public static SpannableString addStrikeLine(String str) {
        SpannableString spStr = new SpannableString(str);
        spStr.setSpan(new StrikethroughSpan(), 0, str.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spStr;
    }

    /**
     * 获取当前时间--字符串形式
     *
     * @return
     */
    public static String getCurrentDate() {
        Calendar cal = Calendar.getInstance();
        return yMdFormater.format(cal.getTime());
    }

    /**
     * 判断是否是今天
     *
     * @param time
     * @return
     */
    public static boolean isToday(String time) {
        return time != null && getCurrentDate().equals(time);

    }

    /**
     * 以友好的方式显示时间
     *
     * @param sdate
     * @return
     */
    public static String friendly_time(String sdate) {
        Date time = toDate(sdate);
        if (time == null) {
            return "Unknown";
        }
        return friendly_time(time);
    }

    public static String friendly_time(Date time, String format) {
        if (time == null) {
            return "";
        }
        String ftime = "";
        Calendar cal = Calendar.getInstance();

        // 判断是否是同一天
        String curDate = yMdFormater.format(cal.getTime());
        String paramDate = yMdFormater.format(time);
        if (curDate.equals(paramDate)) {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0)
                ftime = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000, 1) + "分钟前";
            else
                ftime = hour + "小时前";
            return ftime;
        }

        long lt = time.getTime() / 86400000;
        long ct = cal.getTimeInMillis() / 86400000;
        int days = (int) (ct - lt);
        if (days == 0) {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0)
                ftime = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000, 1) + "分钟前";
            else
                ftime = hour + "小时前";
        } else if (days == 1) {
            ftime = "昨天" + (isEmpty(format) ? "" : new SimpleDateFormat(format).format(time));
        } else if (days == 2) {
            ftime = "前天" + (isEmpty(format) ? "" : new SimpleDateFormat(format).format(time));
        } else if (days > 2 && days <= 10) {
            ftime = days + "天前" + (isEmpty(format) ? "" : new SimpleDateFormat(format).format(time));
        } else if (days > 10) {
            ftime = yMdFormater.format(time);
        }
        return ftime;
    }

    public static String friendly_time(Date time) {
        return friendly_time(time, null);
    }

    public static String timeFormat(Date time, String format) {
        if (time == null) {
            return "Unknown";
        }

        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(time);
    }

    public static String timeFormat(String time, String format) {
        return timeFormat(toDate(time), format);
    }

    public static String timeFormat(String time) {
        return timeFormat(toDate(time), "yyyy-MM-dd HH:mm:ss");
    }

    public static String timeFormat(Date time) {
        return timeFormat(time, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 将字符串转位日期类型
     *
     * @param sdate
     * @return
     */
    public static Date toDate(String sdate) {
        try {
            return yMdHmsFormater.parse(sdate);
        } catch (ParseException e) {
            try {
                return yMdHmFormater.parse(sdate);
            } catch (ParseException e1) {
                try {
                    return yMdFormater.parse(sdate);
                } catch (Exception e2) {
                    return null;
                }
            }
        }
    }

    public static Date toDate(String sDate, String format) {
        try {
            SimpleDateFormat formater = new SimpleDateFormat(format);
            return formater.parse(sDate);
        } catch (Exception e) {
            return null;
        }
    }

    public static String friendly_distance(Double distance) {
        if (distance * 1000 < 1500) {
            return String.format("%.2f", distance * 1000) + "米";
        } else {
            return String.format("%.2f", distance) + "公里";
        }
    }

    public static String friendly_size(long byteSize) {
        if (byteSize / 1024 < 1) {
            return byteSize + "B";
        } else if (byteSize / 1024 / 1024 < 1) {
            return String.format(Locale.CHINA, "%1$.2fKB", (float) byteSize / 1024);
        } else if (byteSize / 1024 / 1024 / 1024 < 1) {
            return String.format(Locale.CHINA, "%1$.2fMB", (float) byteSize / 1024 / 1024);
        } else {
            return String.format(Locale.CHINA, "%1$.2fGB", (float) byteSize / 1024 / 1024 / 1024);
        }
    }

    public static boolean toBool(String value) {
        try {
            return Boolean.parseBoolean(value);
        } catch (Exception ignored) {
        }
        return false;
    }

    public static String decryptUnionCode(String utfString) {
        StringBuilder sb = new StringBuilder();
        int i = -1;
        int pos = 0;

        if ((i = utfString.indexOf("\\u", pos)) == -1) {
            while ((i = utfString.indexOf("u", pos)) != -1) {
                sb.append(utfString.substring(pos, i));
                if (i + 4 < utfString.length()) {
                    pos = i + 5;
                    sb.append((char) Integer.parseInt(utfString.substring(i + 1, i + 5), 16));
                }
            }
        } else {
            while ((i = utfString.indexOf("\\u", pos)) != -1) {
                sb.append(utfString.substring(pos, i));
                if (i + 5 < utfString.length()) {
                    pos = i + 6;
                    sb.append((char) Integer.parseInt(utfString.substring(i + 2, i + 6), 16));
                }
            }
        }

        String result = sb.toString();
        if (!isEmpty(result)) {
            return result;
        }
        return utfString;
    }

    /*将List<String>转换成String,用","隔开*/
    public static String listToString(List<String> stringList) {
        if (stringList == null) {
            return null;
        }
        StringBuilder result = new StringBuilder();
        boolean flag = false;
        for (String string : stringList) {
            if (flag) {
                result.append(",");
            } else {
                flag = true;
            }
            result.append(string);
        }
        return result.toString();
    }
}
